package com.jeeplus.modules.statistics.web;

import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.FileUtils;
import com.jeeplus.common.utils.PageBean;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.web.PageResult;
import com.jeeplus.common.web.Result;
import com.jeeplus.modules.statistics.model.domain.MassesDealWithCount;
import com.jeeplus.modules.statistics.model.domain.MassesTakeNumberCount;
import com.jeeplus.modules.statistics.model.query.HomeStatisticsQuery;
import com.jeeplus.modules.statistics.model.query.MassesListQuery;
import com.jeeplus.modules.statistics.model.query.ReserveQuery;
import com.jeeplus.modules.statistics.model.query.StatisticsQuery;
import com.jeeplus.modules.statistics.model.vo.*;
import com.jeeplus.modules.statistics.service.GXQueueService;
import com.jeeplus.modules.statistics.service.LeaderBoradService;
import com.jeeplus.modules.statistics.service.RegionalMassesStatisticsService;
import com.jeeplus.modules.statistics.service.RegionalStaffStatisticsService;
import com.jeeplus.modules.sys.utils.FileKit;
import com.jeeplus.modules.sys.utils.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import net.sf.json.JSONArray;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.web.bind.annotation.*;

import java.io.FileOutputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * ClassName: DetailsStatisticsController
 * Function:  各区域不同维度统计 控制器
 * Date:      2021/2/24 10:00
 *
 * @author hanKongbin
 * version    V1.0
 */
@RestController
@RequestMapping("/gx/statistics/regional")
@AllArgsConstructor
//@Api(tags = "高新统计统计-各区域详情")
public class RegionalStatisticsController {

    /**
     * 各区域下窗口员工接件统计
     */
    private final RegionalStaffStatisticsService regionalStaffStatisticsService;

    /**
     * 各区域下的办件群众统计
     */
    private final RegionalMassesStatisticsService regionalMassesStatisticsService;

    /**
     * 各区域下的领导看板（主页）
     */
    private final LeaderBoradService leaderBoradService;

    /**
     * 高新排队库
     */
    private final GXQueueService gxQueueService;

    //@ApiOperation("主页")
    @PostMapping("/home")
    public Result<HomeCharts> home(@RequestBody HomeStatisticsQuery query) {
        if(null != UserUtils.getUser())
        query.setUserid("%"+UserUtils.getUser().getId()+"%");
        HomeCharts result = leaderBoradService.findCharts(query);
        if("true".equals(query.getFlag())){
            String fileName = "时间段趋势统计"+ DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            //创建excle
            HSSFWorkbook wb = new HSSFWorkbook();
            HSSFCellStyle cellStyle = wb.createCellStyle();//设置样式
            cellStyle.setBorderBottom(BorderStyle.THIN);//设置下边框
            cellStyle.setBorderLeft(BorderStyle.THIN);//设置左边框
            cellStyle.setBorderRight(BorderStyle.THIN);//设置右边框
            cellStyle.setBorderTop(BorderStyle.THIN);//设置上边框
            cellStyle.setBottomBorderColor((short)1);//设置边框颜色
            cellStyle.setAlignment(HorizontalAlignment.CENTER);//居中
            //通过HSSFWorkbook创建一个HSSFFont
            HSSFFont font = wb.createFont();
            //设置一个字体的颜色2表示红色3表示绿色4表示蓝色5表示黄色6表示紫色7表示亮蓝色8表示黑色9表示白色
            font.setColor((short)8);
            //设置字体的风格：仿宋_GB2312、黑体
            font.setFontName("黑体");
            //设置一个字体的大小,此数值的取值与Excel中的字体大小取值一样
            font.setFontHeightInPoints((short) 12);
            cellStyle.setWrapText(true);//设置自动换行
            //设置背景色
            cellStyle.setFillForegroundColor((short) 13);
            cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            //把该字体应用到当前的样式
            font.setBold(true);
            cellStyle.setFont(font);
            JSONArray json = JSONArray.fromObject(result.getChart2().getXValue());
            HSSFSheet sheet = wb.createSheet("时间段趋势统计");
            try {
                HSSFRow row = null;
                HSSFCell hc = null;
                row = sheet.createRow(0);
                for(int i =0;i<json.size();i++){
                    hc = row.createCell(i);
                    hc.setCellStyle(cellStyle);
                    hc.setCellValue(String.valueOf(json.getString(i)));
                    sheet.setColumnWidth(i, 5000); //第一个参数代表列id(从0开始),第2个参数代表宽度值
                }
                json = JSONArray.fromObject(result.getChart2().getYValue());
                //加载第一次数据集合进入excle
                row = sheet.createRow(1);
                for(int key=0;key<json.size();key++){
                    row.createCell(key).setCellValue(String.valueOf(json.getString(key)));
                }
                //文档输出
                String fileDir = FileKit.getAttachmentDir()+"gxzw/excle/queue/";
                FileUtils.createDirectory(fileDir);
                fileDir = fileDir+fileName;
                FileOutputStream out = new FileOutputStream(fileDir);
                wb.write(out);
                out.flush();
                out.close();
                result.setUrl(fileDir.substring(fileDir.indexOf("userfiles"),fileDir.length()));
            }catch (Exception e){}
            return Result.succeed(result, "获取成功！");
        }else{
            return Result.succeed(result, "获取成功！");
        }

    }

    //@ApiOperation("接件量统计")
    @PostMapping("/piecesReceived")
    public Result<StatisticsXY> piecesReceived(@RequestBody StatisticsQuery query) {
        return regionalStaffStatisticsService.piecesReceivedStatistics(query);
    }

    //@ApiOperation("热度业务统计")
    @PostMapping("/hotBusiness")
    public Result<StatisticsXY> hotBusiness(@RequestBody StatisticsQuery query) {
        return regionalStaffStatisticsService.hotBusStatistics(query);
    }

    //@ApiOperation("业务办理趋势统计")
    @PostMapping("/bussinessTrends")
    public Result<StatisticsXY> bussinessTrends(@RequestBody StatisticsQuery query) {
        return regionalStaffStatisticsService.businessTrendsStatistics(query);
    }

    //@ApiOperation("办件量排名统计")
    @PostMapping("/handleRanking")
    public Result<List<HandleRankingVO>> handleRanking(@RequestBody StatisticsQuery query) {
        return regionalStaffStatisticsService.handleRanking(query);
    }

    //@ApiOperation("评价统计")
    @PostMapping("/appraise")
    public Result appraiseStatistics(@RequestBody StatisticsQuery query) {
        return regionalStaffStatisticsService.appraiseStatistics(query);
    }

    //@ApiOperation("平均等待时间统计")
    @PostMapping("/avgWaitingTime")
    public Result<List<WaitingTimeVO>> avgWaitingTimeStatistics(@RequestBody StatisticsQuery query) {
        return regionalStaffStatisticsService.avgWaitingTimeStatistics(query);
    }

    //@ApiOperation("平均办理时间统计")
    @PostMapping("/avgWinTime")
    public AjaxJson avgWinTime(@RequestBody StatisticsQuery query) {
        return regionalStaffStatisticsService.avgWinTime(query);
    }

    //@ApiOperation("周人流量统计")
    @PostMapping("/weeklyTraffic")
    public Result<StatisticsXY> weeklyTrafficStatistics(@RequestBody StatisticsQuery query) {
        return regionalStaffStatisticsService.weeklyTraffic(query);
    }

    //@ApiOperation("时段人流量统计")
    @PostMapping("/timePeriodTraffic")
    public Result<StatisticsXY> timePeriodTrafficStatistics(@RequestBody StatisticsQuery query) {
        return regionalStaffStatisticsService.timePeriodTraffic(query);
    }

    //@ApiOperation("性别统计")
    @PostMapping("/sex")
    public Result sexStatistics(@RequestBody StatisticsQuery query) {
        return regionalMassesStatisticsService.sexStatistics(query);
    }

    //@ApiOperation("年龄统计")
    @PostMapping("/age")
    public Result ageStatistics(@RequestBody StatisticsQuery query) {
        return regionalMassesStatisticsService.ageStatistics(query);
    }

    //@ApiOperation("居民统计")
    @PostMapping("/resident")
    public Result<ResidentCharts> residentStatistics(@RequestBody StatisticsQuery query) {
        return regionalMassesStatisticsService.residentStatistics(query);
    }

    //@ApiOperation("地区统计")
    @PostMapping("/city")
    public Result cityStatistics(@RequestBody StatisticsQuery query) {
        return regionalMassesStatisticsService.cityStatistics(query);
    }

    //@ApiOperation("全国统计")
    @PostMapping("/province")
    public Result provinceStatistics(@RequestBody StatisticsQuery query) {
        return regionalMassesStatisticsService.provinceStatistics(query);
    }

    //@ApiOperation("群众办件列表")
    @PostMapping("/massesDealWith")
    public PageResult<MassesDealWithCount> dealWithList(@RequestBody MassesListQuery query) {
        return regionalMassesStatisticsService.dealWithList(query);
    }

    //@ApiOperation("群众取号列表")
    @PostMapping("/massesTakeNumber")
    public PageResult<MassesTakeNumberCount> takeNumberList(@RequestBody MassesListQuery query) {
        return regionalMassesStatisticsService.takeNumberList(query);
    }

    //@ApiOperation("人员统计")
    @PostMapping("/staffPiecesReceived")
    public Result<StatisticsXY> staffPiecesReceivedStatistics(@RequestBody StatisticsQuery query) {
        return regionalStaffStatisticsService.staffPiecesReceived(query);
    }

    //@ApiOperation("预约查询")
    @PostMapping("/queryReserve")
    public PageResult<List<ReserveVO>> queryReserve(@RequestBody ReserveQuery query) {
        return gxQueueService.queryReserve(query);
    }

    //@ApiOperation("预约删除")
    @DeleteMapping("/deleteReserve/{id}")
    public Result<Boolean> deleteReserve(@PathVariable("id") String id) {
        return Result.succeed(gxQueueService.deleteReserve(id), "");
    }

    //@ApiOperation("预约业务统计")
    @PostMapping("/reserveBusiness")
    public Result<StatisticsXY> queryReserve(@RequestBody StatisticsQuery query) {
        return gxQueueService.reserveBusiness(query);
    }

}
